<template>
  <BeEcharts ref="bottomBarChartRef" class="chart-box" />
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { BeEcharts, useEcharts } from '@/components/basics/BeEcharts'
import * as echarts from 'echarts/core'

// state
const bottomBarChartRef = ref()
const { renderEcharts } = useEcharts(bottomBarChartRef)
const dataValues = [1900, 1700, 1500, 1300, 1100]
const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
})

onMounted(() => {
  const maxValue = Math.max(...props.chartData.map((item: any) => item.count))
  //生成背景条
  const bgValues = Array(props.chartData.length).fill(maxValue + 20)
  renderEcharts({
    title: {
      text: '告警类型排名TOP5',
      left: 'left',
      top: 0,
      textStyle: {
        color: '#ffffff',
        fontSize: 14
      }
    },
    grid: {
      left: '0%',
      right: '0%',
      bottom: '0%',
      top: '20%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params: any) {
        // 只返回数据条的信息
        const realData = params.find((item: any) => item.seriesIndex === 1) // 第二个 series 是数据条
        return `${realData.name || realData.axisValue}: ${realData.value} 次`
      }
    },
    xAxis: {
      type: 'value',
      show: false
    },
    yAxis: {
      type: 'category',
      data: props.chartData.map((item: any) => item.eventTypeName),
      axisLabel: {
        color: '#ffffff'
      },
      axisLine: { show: false },
      axisTick: { show: false }
    },
    series: [
      // 背景条
      {
        type: 'bar',
        data: bgValues,
        barWidth: 14, // 背景条宽度增加，使其比数据条宽
        barGap: '-100%', // 关键配置：设置为负值实现重叠
        itemStyle: {
          borderRadius: 0,
          color: 'rgba(255, 255, 255, 0.1)'
        },
        label: {
          show: true,
          position: 'insideRight', // 使用内置的insideRight位置
          offset: [5, -16], // 微调偏移量，使标签位于右上方
          valueAnimation: true,
          color: '#fff',
          fontSize: 12,
          formatter: (params: any) => `${props.chartData[params.dataIndex]?.count} 次`
        },
        z: 1
      },
      // 数据条
      {
        type: 'bar',
        data: props.chartData.map((item: any) => item.count),
        barWidth: 14, // 数据条宽度小于背景条
        barGap: '-100%', // 关键配置：设置为负值实现重叠
        itemStyle: {
          borderRadius: 0,
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#144b9e' },
            { offset: 1, color: '#3BAEFF' }
          ])
        },
        z: 2
      }
    ]
  })
})
</script>
